package com.ruoyi.cat.service.impl;

import com.ruoyi.cat.domain.CatBasedataTable;
import com.ruoyi.cat.domain.CatIprecordTable;
import com.ruoyi.cat.domain.CatTradedetailTable;
import com.ruoyi.cat.domain.CatUserbasicTable;
import com.ruoyi.cat.domain.DTO.ArticletaskDTO;
import com.ruoyi.cat.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

@Service
@Slf4j
public class WritingsImpl implements WritingsService {



    @Autowired
    private ICatArticletaskTableService articleTaskService;


    @Autowired
    private ICatUserbasicTableService userService;

    @Autowired
    private ICatIprecordTableService ipRecordService;

    @Autowired
    private ICatTradedetailTableService tradeDetailService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void processArticleReward(CatIprecordTable record, CatBasedataTable baseData) {
        ArticletaskDTO article = articleTaskService.selectCatArticletaskById(record.getArticleId());
        if (StringUtils.isEmpty(article.getProvince())){
            log.warn("没有地址,不处理：{}", record.getArticleId());
            return;        }
        if (article == null) {
            log.warn("文章不存在，文章ID：{}", record.getArticleId());
            return;
        }

        // 获取分享用户信息
        CatUserbasicTable sharer = userService.selectCatUserbasicTableById(record.getShareUserId());
        if (sharer == null) {
            log.warn("用户不存在，用户ID：{}", record.getShareUserId());
            return;
        }
        // 获取系统参数
        //基础利润 - 转换百分比为小数
        BigDecimal baseProfit = baseData.getBaseProfit().divide(new BigDecimal("100"), 4, RoundingMode.HALF_UP);
        //基础成本
        BigDecimal baseCost = baseData.getBaseCost();
        //地区奖励 - 转换百分比为小数
        BigDecimal offsiteDiscountRate = baseData.getOffsiteDiscountRate().divide(new BigDecimal("100"), 4, RoundingMode.HALF_UP);
        //推荐奖励 - 转换百分比为小数
        BigDecimal introduceReward = baseData.getIntroduceReward().divide(new BigDecimal("100"), 4, RoundingMode.HALF_UP);
        //目标人数
        Long targetNum = article.getTargetNum();

        record.setAreaValue(article.getCity());
        //本地ip数量
        CatIprecordTable localRecord = ipRecordService.getStaskData(record);
        //异地ip数量
        CatIprecordTable remoteRecord = ipRecordService.getStaskDataNo(record);

        // 初始化本地和异地访问量
        Long localQuantity = (localRecord != null) ? localRecord.getQuantity() : 0L;
        Long remoteQuantity = (remoteRecord != null) ? remoteRecord.getQuantity() : 0L;

        Long totalQuantity = localQuantity + remoteQuantity;

        // 计算单位单价：(BaseCost * TargetNum * (1-BaseProfit) / TargetNum)
        System.out.println("BaseCost: " + baseCost);
        System.out.println("BaseProfit: " + baseProfit);
        System.out.println("TargetNum: " + targetNum);
        System.out.println("LocalQuantity: " + localQuantity);

        BigDecimal unitPrice = baseCost
                .multiply(BigDecimal.ONE.subtract(baseProfit))
                .setScale(4, RoundingMode.HALF_UP);  // 0.010 * 0.9980 = 0.00998

        BigDecimal localReward = unitPrice
                .multiply(BigDecimal.valueOf(localQuantity))  // 0.00998 * 3
                .setScale(4, RoundingMode.HALF_UP);          // = 0.02994 → 0.0300


        // 计算异地收益：unitPrice * OffsiteDiscountRate * 异地IP数
        BigDecimal remoteReward = unitPrice
                .multiply(offsiteDiscountRate)
                .multiply(BigDecimal.valueOf(remoteQuantity))
                .setScale(4, RoundingMode.HALF_UP);
        // 个人总收益
        BigDecimal personalReward = localReward.add(remoteReward);

        log.info("用户[ID:{}]活动[ID:{}] 本地收益：{}，异地收益：{}，总收益：{}",
                sharer.getId(), article.getId(), localReward, remoteReward, personalReward);
        // 检查本地 IP 数量和异地 IP 数量是否都不为 0
        if (localQuantity > 0 && remoteQuantity > 0) {
            BigDecimal totalPotentialReward = baseCost
                    .multiply(BigDecimal.valueOf(targetNum))
                    .multiply(BigDecimal.ONE.subtract(baseProfit));

            BigDecimal localCost = totalPotentialReward
                    .divide(BigDecimal.valueOf(10000), 6, RoundingMode.HALF_UP)
                    .multiply(BigDecimal.valueOf(localQuantity));

            BigDecimal remoteCost = totalPotentialReward
                    .divide(BigDecimal.valueOf(10000), 6, RoundingMode.HALF_UP)
                    .multiply(offsiteDiscountRate)
                    .multiply(BigDecimal.valueOf(remoteQuantity));

            BigDecimal platformReward = totalPotentialReward.subtract(localCost).subtract(remoteCost);
            if (platformReward.compareTo(BigDecimal.ZERO) != 0) {
                // 记录平台收益交易明细
                recordTradeDetail(sharer, article.getId(), sharer.getId(),
                        platformReward, null, "2",
                        totalQuantity, "品牌推广收益", "1");
            }
            log.info("用户[ID:{}]活动[ID:{}] 本地成本：{}，异地成本：{}，平台收益：{}",
                    sharer.getId(), article.getId(), localCost, remoteCost, platformReward);
        }

        //获取下级所有的异地ip数量
        List<CatUserbasicTable> list =  getTotalUvCountX(record);
        for (CatUserbasicTable catUserbasicTable : list) {
            record.setShareUserId(catUserbasicTable.getId());
            //本地ip数量
            CatIprecordTable localRecord1= ipRecordService.getStaskData(record);
            //异地ip数量
            CatIprecordTable remoteRecord2 = ipRecordService.getStaskDataNo(record);
            // 初始化本地和异地访问量
            Long localQuantity1 = (localRecord1!= null)? localRecord1.getQuantity() : 0L;
            Long remoteQuantity2 = (remoteRecord2!= null)? remoteRecord2.getQuantity() : 0L;
            if (remoteQuantity2> 0){
                // 计算本地收益：introduceReward * 异地IP数
                BigDecimal localReward1 = introduceReward
                        .multiply(BigDecimal.valueOf(remoteQuantity2))
                        .setScale(2, RoundingMode.HALF_UP);
                log.info("下级给我的收益：{} ",localReward1);
                // 记录平台收益交易明细
                if (localReward1.compareTo(BigDecimal.ZERO) != 0) {
                    log.info("下级给我的收益2  ：{} ",localReward1);
                    recordTradeDetail(sharer, article.getId(), catUserbasicTable.getId(),
                            localReward1, sharer.getId(), "3",
                            null, "品牌推广收益", "1");
                }
            }

           Long count = localQuantity1+remoteQuantity2;

            if (count > 0) {
                BigDecimal unitPrice1 = baseCost
                        .multiply(BigDecimal.ONE.subtract(baseProfit))
                        .setScale(4, RoundingMode.HALF_UP);

                BigDecimal downlineConversionReward = unitPrice1
                        .multiply(offsiteDiscountRate)
                        .multiply(BigDecimal.valueOf(count))
                        .multiply(introduceReward)
                        .setScale(2, RoundingMode.HALF_UP);

                log.info("下级[ID:{}]给我的转化收益：{}，总IP数：{}",
                        catUserbasicTable.getId(), downlineConversionReward, count);

                // 计算推荐人获得的助力数量
                long helpingPeople = Math.round(count * introduceReward.doubleValue());

                // 记录平台收益交易明细
                recordTradeDetail(sharer, article.getId(), sharer.getId(),
                        downlineConversionReward, catUserbasicTable.getId(), "0",
                        helpingPeople, "品牌推广团队助力收益", "1");
            }

        }

        record.setShareUserId(sharer.getId());
        //查询父类,给父类产生收益
        //Long count =  ipRecordService.countShareRecord(record);
        CatUserbasicTable referrer = userService.selectCatUserbasicTableById(sharer.getReferenceId());
        if (referrer != null) {
            //异地ip数量
            CatIprecordTable remoteRecord2 = ipRecordService.getStaskDataNo(record);
            Long remoteQuantity2 = (remoteRecord2!= null)? remoteRecord2.getQuantity() : 0L;
            if (remoteQuantity2> 0){
                // 计算本地收益：introduceReward * 异地IP数
                BigDecimal localReward1 = introduceReward
                        .multiply(BigDecimal.valueOf(remoteQuantity2))
                        .setScale(2, RoundingMode.HALF_UP);
                log.info("我给上级的收益：{} ",localReward1);

                if (localReward1.compareTo(personalReward) <= 0) {
                    personalReward = personalReward.subtract(localReward1);
                    log.info("实际扣除上级收益后剩余金额：{}", personalReward);
                } else {
                    log.warn("上级收益 {} 超过个人总收益 {}，不进行扣除", localReward1, personalReward);
                }

                // 记录平台收益交易明细
                recordTradeDetail(sharer, article.getId(), referrer.getId(),
                        localReward1, sharer.getId(), "4",
                        null, "品牌推广收益", "1");
            }

          //  personalReward = personalReward.subtract(localReward1);

        }

        // 记录个人收益交易明细
        recordTradeDetail(sharer, article.getId(), sharer.getId(),
                personalReward, null, "0",
                totalQuantity, "品牌推广收益", "1");

    }

    public static void main(String[] args) {
        BigDecimal baseCost = new BigDecimal("0.01");
        BigDecimal baseProfit = new BigDecimal("0.02");
        long targetNum = 10000;
        // 根据计算结果调整 localQuantity 的值
        long localQuantity = 3;

        BigDecimal unitPrice = baseCost
                .multiply(BigDecimal.valueOf(targetNum))
                .multiply(BigDecimal.ONE.subtract(baseProfit))
                .divide(BigDecimal.valueOf(targetNum), 4, RoundingMode.HALF_UP);

        BigDecimal localReward = unitPrice
                .multiply(BigDecimal.valueOf(localQuantity))
                .setScale(3, RoundingMode.HALF_UP);

        System.out.println("本地收益: " + localReward);
    }



    /**
     * 记录交易明细
     */
    private void recordTradeDetail(CatUserbasicTable user, Long activityId, Long userId,
                                   BigDecimal amount, Long profitUserId, String income,
                                   Long helpingPeople, String tradeTitle, String type) {
        if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) {
            return; // 金额为零或负数不记录
        }

        CatTradedetailTable tradeDetail = new CatTradedetailTable();
        tradeDetail.setActivityId(activityId);
        tradeDetail.setUserId(userId);
        tradeDetail.setTradeType("0"); // 未结算
        tradeDetail.setTradeTitle(tradeTitle);
        tradeDetail.setTradeNum(amount);
        tradeDetail.setType(type);
        tradeDetail.setProfitUserId(profitUserId);
        tradeDetail.setIncome(income);
        tradeDetail.setHelpingPeople(helpingPeople);

        // 插入交易记录
        tradeDetailService.insertCatTradedetailTable(tradeDetail);

        // 更新用户冻结余额
        updateUserBalance(user, amount);

        log.info("记录交易明细成功：用户ID={}，活动ID={}，金额={}，类型={}",
                userId, activityId, amount, type);
    }



    /**
     * 更新用户冻结余额
     */
    private void updateUserBalance(CatUserbasicTable user, BigDecimal amount) {
        if (amount.compareTo(BigDecimal.ZERO) <= 0) {
            return; // 金额为零或负数不处理
        }

        // 处理冻结金额为null的情况
        BigDecimal freezeDeposits = user.getFreezeDeposits() != null ? user.getFreezeDeposits() : BigDecimal.ZERO;
        user.setFreezeDeposits(freezeDeposits.add(amount));

        int result = userService.updateCatUserbasicTable(user);
        if (result != 1) {
            log.warn("更新用户冻结余额失败，用户ID：{}", user.getId());
        }
    }

    /**
     * 获取所有下线产生的UV总数
     * @param record
     * @return
     */
    private List<CatUserbasicTable> getTotalUvCountX(CatIprecordTable record) {
        List<CatUserbasicTable> list =  userService.countByReferenceData(record.getShareUserId());
        return list;
    }
}
